# -*- coding: utf-8 -*-
#!/usr/bin/env python

import sqlite3 as db
import sys

DATABASE = "sqlite/db.dat"


class Database:
    conn = None

    """
        Kontruktor, tworzy połączenie z bazą
    """

    def __init__(self):
        try:
            self.conn = db.connect(DATABASE)

        except db.Error, e:
            print "Error %s:" % e.args[0]
            sys.exit(1)

    """
        Destruktor, zamyka połączenie z bazą
    """

    def __del__(self):
        if (self.conn is not None):
            self.conn.close()

    """
        Pobiera z bazy danych wszystkie video
    """
    def get_videos(self):
        with self.conn:

            cur = self.conn.cursor()
            cur.execute("SELECT * FROM Videos")

            rows = cur.fetchall()
            return rows

    """
        Dodaje nowy film do bazy
    """
    def add_video(self, title, year, genre):
        with self.conn:

            query = "INSERT INTO Videos (Name, Year, Genre)"
            query += " VALUES ('" + title + "', " + year + ", '" + genre + "')"

            cur = self.conn.cursor()
            cur.execute(query)

            return cur.lastrowid

    def delete_video(self, id_del):
        with self.conn:

            cur = self.conn.cursor()
            cur.execute("DELETE FROM Videos WHERE id=" + str(id_del))
            return True if cur.rowcount == 1 else False

    def delete_rent(self, rent_id):
        with self.conn:

            cur = self.conn.cursor()
            cur.execute("DELETE FROM Rent WHERE id=" + str(rent_id))
            return 1#cur.lastrowid

    def add_rent(self, movie_id, user_name):
        with self.conn:

            cur = self.conn.cursor()
            cur.execute("INSERT INTO Rent (MovieId, UserName, Date) VALUES (" + movie_id + ", '" + user_name + "', DATETIME('now'))")

            return cur.lastrowid

    def get_rents(self):
        with self.conn:

            cur = self.conn.cursor()
            cur.execute("SELECT Rent.Id, Name, Year, UserName, Date FROM Rent LEFT JOIN Videos ON Rent.MovieId = Videos.id")

            rows = cur.fetchall()
            return rows

    def check_rents(self, movie_id):
        with self.conn:

            cur = self.conn.cursor()
            cur.execute("SELECT COUNT(*) FROM Rent WHERE MovieId = " + movie_id)

            rows = cur.fetchall()
            return (rows[0] == "0")


